package cn.smile.annotations.utils;

import cn.smile.annotations.ExcelColumn;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 关于注解的操作
 *
 * @Author: 毛苏宇
 * User: me
 * Date: 2019/12/1
 * Time: 17:18
 * Description: 获取注解属性
 */
public class AnnotationTool {

    /**
     * 获取类中成员属性的所有注解值
     *
     * @param targetClass 目标类
     * @return
     * @throws Exception NULL
     */
    public static String[] getExcelColumnAnnotationValues(Class targetClass) throws Exception {
        //成员属性上的所有注解
        List<ExcelColumn> customAnnotations = getExcelColumnAnnotationList(targetClass);
        final int listSize = customAnnotations.size();
        //注解上所有的值
        String[] values = new String[listSize];
        for (int i = 0; i < listSize; i++) {
            values[i] = customAnnotations.get(i).value();
        }
        return values;
    }

    /**
     * 获取所有成员属性
     * @param targetClass 目标类
     * @return
     */
    public static Field[] getFields(Class targetClass){
        return targetClass.getDeclaredFields();
    }


    /**
     * 得到类下的所有ExcelColumn注解
     * @param targetClass 目标类
     * @return
     * @throws Exception
     */
    public static List<ExcelColumn> getExcelColumnAnnotationList(Class targetClass) throws Exception{
        //装载ExcelColumn的容器
        List<ExcelColumn> customAnnotations = new ArrayList<ExcelColumn>();
        //获取所有成员属性
        final Field[] fields = getFields(targetClass);
        for (Field field : fields) {
            final ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
            if (null!=annotation) {
                customAnnotations.add(annotation);
            }
            continue;
        }
        //有多少个注解
        final int size = customAnnotations.size();
        if (size == 0) {
            throw new Exception(targetClass.getName() + "类中成员属性不能没有" + ExcelColumn.class.getName() + "注解");
        }
        return customAnnotations;
    }

}
